package com.yunxun.amqp;
import com.google.gson.Gson;
import com.rabbitmq.client.AMQP;
import com.yunxun.entity.ArticleEntity;
import com.yunxun.entity.MessageEntity;
import com.yunxun.service.ArticleService;
import com.yunxun.service.MessageService;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.util.List;

@Configuration
public class RabbitmqConfig {
    @Autowired
    MessageService messageService;
    @Autowired
    ArticleService articleService;
    @Value("${rabbitmq.host}")
    private String host;
    @Value("${rabbitmq.username}")
    private String username;
    @Value("${rabbitmq.password}")
    private String passwd;
    @Value("${rabbitmq.port}")
    private int port;
    @Value("${rabbitmq.publish-confirm}")
    private boolean publisherConfirm;

    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(passwd);
        connectionFactory.setPublisherConfirms(publisherConfirm); //必须要设置
        return connectionFactory;
    }

    @Bean
    public Queue messageQueue(){
        return new Queue("messageQueue");
    }
    @Bean
    public Queue articleQueue(){
        return new Queue("articleQueue");
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("cnbetaExchange");
    }
    @Bean
    public Binding messageBinding(Queue messageQueue,DirectExchange cnbetaExchange){
        return BindingBuilder.bind(messageQueue).to(cnbetaExchange).with("message");
    }

    @Bean
    public Binding articleBinding(Queue articleQueue,DirectExchange cnbetaExchange){
        return BindingBuilder.bind(articleQueue).to(cnbetaExchange).with("article");
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    //必须是prototype类型
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }

    @Bean
    public SimpleMessageListenerContainer messageContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
        container.setQueues(messageQueue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {
            public void onMessage(Message message, com.rabbitmq.client.Channel channel) throws Exception {
                byte[] body = message.getBody();
                MessageEntity messageEntity = new MessageEntity();
                int typeValue = Integer.parseInt(new String(body));
                messageEntity.setTypeValue(typeValue);
                messageService.queryMessageByTypeValue(messageEntity);
                List<MessageEntity> messageEntities = messageService.queryMessageByTypeValue(messageEntity);
                Gson gson = new Gson();
                String json = gson.toJson(messageEntities);
                MessageProperties  properties = message.getMessageProperties();
                String replyTo = properties.getReplyTo();
                String correlationId = properties.getCorrelationId();
                AMQP.BasicProperties replyProperties = new AMQP.BasicProperties().builder().deliveryMode(2).contentType("UTF-8").correlationId(correlationId).build();
                channel.basicPublish("", replyTo, replyProperties, json.getBytes());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
            }
        });
        return container;
    }
    @Bean
    public SimpleMessageListenerContainer articleContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
        container.setQueues(articleQueue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {
            public void onMessage(Message message, com.rabbitmq.client.Channel channel) throws Exception {
                byte[] body = message.getBody();
                ArticleEntity articleEntity = new ArticleEntity();
                int mid = Integer.parseInt(new String(body));
                articleEntity.setMid(mid);
                articleEntity = articleService.selectByMid(articleEntity);
                Gson gson = new Gson();
                String json = gson.toJson(articleEntity);
                MessageProperties  properties = message.getMessageProperties();
                String replyTo = properties.getReplyTo();
                String correlationId = properties.getCorrelationId();
                AMQP.BasicProperties replyProperties = new AMQP.BasicProperties().builder().deliveryMode(2).contentType("UTF-8").correlationId(correlationId).build();
                channel.basicPublish("", replyTo, replyProperties, json.getBytes());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
            }
        });
        return container;
    }
}
